package com.kalvan.commons.db.system;

import com.kalvan.commons.db.DataSourceConstants;
import com.kalvan.core.utils.ByteUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.shardingsphere.shardingjdbc.api.yaml.YamlShardingDataSourceFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.SQLException;

/***
 * manager数据源加载扫描
 *
 * @author kalvan
 * @date 2019-06-01 02:29:27
 */
@Configuration
@MapperScan(basePackages = DataSourceConstants.SYSTEM_MAPPER_PACKAGE, sqlSessionFactoryRef = DataSourceConstants.SYSTEM_SESSION_FACTORY)
public class SystemDataSourceConfig {
    @Value(DataSourceConstants.SYSTEM_SHARDING_YML)
    private String yamlPath;

    @Bean
    public DataSource systemDataSource() throws SQLException, IOException {
        DataSource dataSource = YamlShardingDataSourceFactory
                .createDataSource(ByteUtils.getByte(this.getClass().getResourceAsStream(yamlPath)));
        return dataSource;
    }

    @Bean
    public SqlSessionFactory systemSessionFactory(@Qualifier(DataSourceConstants.SYSTEM_DATA_SOURCE) DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources(DataSourceConstants.SYSTEM_MAPPER_PATH));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate systemSqlSessionTemplate(
            @Qualifier(DataSourceConstants.SYSTEM_SESSION_FACTORY) SqlSessionFactory sqlSessionFactory) {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);
        return template;
    }

    @Bean
    public DataSourceTransactionManager systemTransactionManager(@Qualifier(DataSourceConstants.SYSTEM_DATA_SOURCE) DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}
